<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { Locale } from 'vant'
import { useConfigStore } from '@/stores/config'
// 自己写的滚动代码
definePageMeta({
  layout: 'default-home',
  // name: 'home',
  title: 'home',
  i18n: 'menu.home',
});
const configStore = useConfigStore();
const { t, setLocale } = useI18n();
const show = ref(false)
const active = ref(0);
const userStore = useUserStore()
const menuList = reactive([
  { title: "home_page.leftMenu.hots", icon: 'fire-o', urls: 'img/hot.png', url: 'img/un-hot.png' },
  { title: "home_page.leftMenu.favorite", icon: 'like-o', urls: 'img/love.png', url: 'img/un-love.png' },
  { title: "home_page.leftMenu.slots", icon: 'gift-o', urls: 'img/slots.png', url: 'img/un-slots.png', logo: '' },
  { title: "home_page.leftMenu.chess", icon: 'smile-o', urls: 'img/qp.png', url: 'img/un-qp.png', logo: '' },
  { title: "home_page.leftMenu.fish", icon: 'gem-o', urls: 'img/by.png', url: 'img/un-by.png', logo: '' },
  { title: "home_page.leftMenu.person", icon: 'contact-o', urls: 'img/zr.png', url: 'img/un-zr.png', logo: '' },
  { title: "home_page.leftMenu.sport", icon: 'flag-o', urls: 'img/sport.png', url: 'img/un-sport.png', logo: '' },
  { title: "home_page.leftMenu.lottery", icon: 'balance-o', urls: 'img/cp.png', url: 'img/un-cp.png', logo: '' },
]);
const langArr = ref([
  { name: '中文', value: 'zh-CN', url: '/img/en.png', checked: false },
  { name: 'English', value: 'en-US', url: '/img/en.png', checked: false },
  { name: 'Indonesia', value: 'indon', url: '/img/indon.png', checked: false },
  { name: 'Myanmar', value: 'mm', url: '/img/mm.png', checked: false },
  { name: 'Malaysia', value: 'mys', url: '/img/mys.png', checked: false },
  { name: 'Thailand', value: 'th', url: '/img/th.png', checked: false },
  { name: 'Vietnam', value: 'vt', url: '/img/vt.png', checked: false },
])
// 当前语言
const curLangObj = ref({
  name: 'English',
  value: 'en-US',
  checked: true,
  url: '/img/en.png'
})
// 语言切换事件
const changeLang = (v: any) => {
  setLocale(v.value)
  Locale.use(v.value)
  localStorage.setItem('lang', v.value)
  show.value = false;
  curLangObj.value = v
  v.checked = true;
};
//初始化语言
function initLanguage() {
  const lang = localStorage.getItem('lang') || 'en-US';//默认英语
  const matchedLang = langArr.value.find(v => v.value === lang);
  if (matchedLang) {
    matchedLang.checked = true
    curLangObj.value = matchedLang;
  }
}

// 在 setup 中调用一次
onMounted(() => {
  initLanguage();
});
//火热和收藏就3列显示，其他一列
const columnNum = computed(() => {
  return active.value === 0 || active.value === 1 ? 2 : 1;
});
const gameArr = ref([
  {
    id: 1,
    name: "游戏1",
    type: "jl",
    img: "/game/jili_icon1.png",
    logo: 'img/jl.png',
    like: false
  },
  {
    id: 2,
    name: "游戏2",
    type: "luva",
    img: "/game/luva_icon1.png",
    logo: 'img/luva.png',
    like: true
  },
  {
    id: 3,
    name: "游戏3",
    type: "pp",
    img: "/game/pp_icon1.png",
    logo: 'img/pp.png',
    like: false
  },
  {
    id: 4,
    name: "游戏1",
    type: "pg",
    img: "/game/pg_icon1.png",
    logo: 'img/pg.png',
    like: false
  },
  {
    id: 5,
    name: "游戏2",
    type: "jl",
    img: "/game/jili_icon2.png",
    logo: 'img/jl.png',
    like: false
  },
  {
    id: 6,
    name: "游戏3",
    type: "luva",
    img: "/game/luva_icon2.png",
    logo: 'img/luva.png',
    like: false
  },
  {
    id: 7,
    name: "游戏1",
    type: "jl",
    img: "/game/jili_icon3.png",
    logo: 'img/jl.png',
    like: false
  },
  {
    id: 8,
    name: "游戏2",
    type: "pp",
    img: "/game/pp_icon2.png",
    logo: 'img/pp.png',
    like: false
  }
]);
const goDetail = (item: any) => {
  // 是火热和收藏就先不跳转
  if (specialIndex.value == 0 || specialIndex.value == 1) {
    return
  }
  // 进入详情页不展示搜索条件
  configStore.setSearchStatus(false)
  router.push('/home/details')
}
const specialIndex = ref(0)
const getGame = (item: any, index: number) => {
  // console.log(444,);
  specialIndex.value = index

  active.value = index
}
const router = useRouter();
const goLogin = () => {
  router.push('/login')
}
const goRegister = () => {
  router.push('/register')
}
const goAnnouncement = () => {
  router.push('/home/announcement')
}
const whatType = (v: string, disabled: boolean) => {
  switch (v) {
    case 'luva':
      return 'right-item-luva'
      return disabled ? 'opacity-25 right-item-luva' : 'right-item-luva'
    case 'pp':
      return 'right-item-pp'
      return disabled ? 'opacity-25 right-item-pp' : 'right-item-pp'
    case 'pg':
      return 'right-item-pg'
      return disabled ? 'opacity-25 right-item-pg' : 'right-item-pg'
    case 'jl':
      return 'right-item-jl'
      return disabled ? 'opacity-25 right-item-jl' : 'right-item-jl'
  }
}
const close = ref(true)
const adviseRef = ref(null)
const topRef = ref(null)
const logoRef = ref(null)
const noticeRef = ref(null)
const adviseHeight = ref(0)
const logoHeight = ref(0)
const twoBoxHeight = ref(0)
onMounted(async () => {
  // 获取用户信息
  await userStore.getUserInfo(0)
  // console.log('home--用户信息', userStore.user);
  nextTick(() => {
    if (adviseRef?.value) {
      adviseHeight.value = adviseRef.value?.offsetHeight - 1;
    }
    if (adviseRef?.value && noticeRef?.value && logoRef.value) {
      twoBoxHeight.value = logoRef.value?.offsetHeight + adviseRef.value?.offsetHeight - 3
      logoHeight.value = logoRef.value?.offsetHeight
    }
  });
});

const startY = ref(0)
const endY = ref(0)
const rightContRef = ref<HTMLElement | null>(null)
const triggerRateTextAnimation = () => {
  const rateEls = rightContRef.value?.querySelectorAll('.rate-text')
  rateEls?.forEach((el: Element) => {
    el.classList.remove('animate')
    // 强制 reflow
    void (el as HTMLElement).offsetWidth
    el.classList.add('animate')
  })
}
const onTouchStart = (e: TouchEvent) => {
  startY.value = e.touches[0]?.clientY||0
}

const onTouchEnd = async (e: TouchEvent) => {
  endY.value = e.changedTouches[0]?.clientY||0
  const deltaY = endY.value - startY.value
  const threshold = 50

  const content = rightContRef.value
  if (!content) return

  const scrollTop = content.scrollTop
  const scrollHeight = content.scrollHeight
  const clientHeight = content.clientHeight

  const isAtTop = scrollTop <= 0
  const isAtBottom = scrollTop + clientHeight >= scrollHeight - 2

  if (Math.abs(deltaY) < threshold) return

  if (deltaY < 0 && isAtBottom) {
    // 向上滑 & 到底，切换下一个菜单，滚到顶部
    switchMenu('next', true)
  } else if (deltaY > 0 && isAtTop) {
    // 向下滑 & 到顶，切换上一个菜单，缓慢滚到底再往上
    switchMenu('prev', false)
  }
}

const switchMenu = (direction: 'next' | 'prev', scrollToTop: boolean) => {
  let newIndex = active.value

  if (direction === 'next') {
    newIndex = Math.min(menuList.length - 1, active.value + 1)
  } else {
    newIndex = Math.max(0, active.value - 1)
  }

  if (newIndex !== active.value) {
    active.value = newIndex
    specialIndex.value = newIndex
    getGame(menuList[newIndex], newIndex)

    nextTick(async () => {
      const el = rightContRef.value
      if (!el) return

      if (scrollToTop) {
        el.scrollTo({ top: 0, behavior: 'smooth' })
      } else {
        el.scrollTop = el.scrollHeight // 先跳到底
        await sleep(200)
        // 缓慢往上滚动到底部顶部

        await scrollToTopSmoothly(el)
      }

      triggerRateTextAnimation()
    })
  }
}
// 滚动之间的间隔时间
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
// 进入上一个菜单后，平滑从底部滚动到顶部
const scrollToTopSmoothly = async (el: HTMLElement) => {
  let maxScrollTop = el.scrollHeight - el.clientHeight

  // 先滚到底部
  el.scrollTop = maxScrollTop

  while (el.scrollTop > 0) {
    const scrollStep = Math.min(el.scrollTop, 60) // 每次向上最多滚动 60
    el.scrollTop -= scrollStep
    await sleep(200)
  }
}
</script>

<template>
  <div>
    <!-- 下载广告 -->
    <van-sticky>
      <div ref="adviseRef" class=" py-8 px-12 bg-#ffffff" v-if="close">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <van-icon name="cross" @click="close = false" size="30" color="#ccc" />
            <img class="w-35 h-35 mx-10 rounded-2" src="/img/down_icon.png" />
            <div>
              <div class="font-bold color-#2b2e3e text-14">WildWin APP</div>
              <div class="text-10 text-#80859c">描述文本xxxxxxx</div>
            </div>
          </div>
          <div class="border-1 border-gray px-10 py-4 rounded-6 text-14 bg-#179dff color-#ffffff">
            {{ t('home_page.nowDown') }}</div>
        </div>
      </div>
    </van-sticky>
    <!-- 顶部logo -->
    <van-sticky :offset-top="close ? adviseHeight : 0">
      <div ref="logoRef" class="py-5 px-12 bg-[var(--c-primary-100)]">
        <div class="flex items-center justify-between">
          <div class="flex items-center justify-center">
            <img class="w-36 h-36 rounded-full" src="/img/logo_icon.png" />
            <!-- <van-divider vertical :style="{ borderColor: 'gray', height: '35px' }" /> -->
            <div class="ml-10">
              <div class="font-bold color-#00041c">TC</div>
              <div class="text-10 text-#8b94a4">GAMING</div>
            </div>
          </div>
          <div class="flex justify-center items-center">
            <div class="text-10 color-#7e8796">{{ t('home_page.PerUrl') }}:wangye.com</div>
            <img class="w-24 h-24 rounded-full mx-6" :src="curLangObj.url" @click='show = true' />
            <div class="color-#1e2632 text-12" @click='show = true'>{{ curLangObj.name }}</div>
          </div>
        </div>
      </div>
    </van-sticky>
    <!-- 主体部分 -->
    <div class="main-content px-12">
      <div ref="topRef">
        <!-- 轮播图 -->
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <!-- <van-swipe-item v-for="item in swipeList" :key="item.url">
        <img class="w-full h-150 rounded-10" :src="item.url" />
      </van-swipe-item> -->
          <van-swipe-item>
            <img class="w-full h-150 rounded-10" src="~/assets/images/1.jpg" />
          </van-swipe-item>
          <van-swipe-item>
            <img class="w-full h-150 rounded-10" src="~/assets/images/2.jpg" />
          </van-swipe-item>
          <van-swipe-item>
            <img class="w-full h-150 rounded-10" src="~/assets/images/3.jpg" />
          </van-swipe-item>
          <van-swipe-item>
            <img class="w-full h-150 rounded-10" src="~/assets/images/4.jpg" />
          </van-swipe-item>
        </van-swipe>
        <!-- 消息通知栏 -->
        <van-notice-bar ref="noticeRef" @click="goAnnouncement" color="#7d86a4" text="无论我们能活多久，我们能够享受的只有无法分割的此刻，此外别无其他。"
          background="var(--c-primary-100)">
          <template #left-icon>
            <img src="~/assets/images/web_icon_gb.png" class="w-14 h-14 mr-4" />
          </template>
        </van-notice-bar>
      </div>
      <van-sticky :offset-top="close ? twoBoxHeight : logoHeight" class="bg-[var(--c-primary-100)]">
        <!-- 登录 注册 -->
        <div class="">
          <div v-if="!userStore.isLogin" class="flex justify-between items-center text-dark">
            <div>
              <div class="font-bold text-16 color-#28323e"> {{ t("home_page.no_login") }}</div>
              <div class="text-12 text-[var(--c-text)]"> {{ t("home_page.no_login_desc") }}</div>
            </div>
            <van-space class="login">
              <div class="home-btn w-80" @click="goRegister"> {{ t("home_page.register") }}</div>
              <div class="home-btn w-80" @click="goLogin">{{ t("home_page.login") }}</div>
            </van-space>
          </div>
          <div v-else class="flex justify-between items-center mt-5">
            <div>
              <div><span> {{ userStore.user.name }}</span><span class="ml-10">{{ userStore.user.id }}</span></div>
              <!-- <div class="text-12 text-gray"> ID: {{ userStore.user.id }}</div> -->
              <div class="flex items-center relative w-49">
                <img class="w-15 h-15 relative z-2" src="/img/vip-v.png" alt="">
                <img class="w-48 mr-10 absolute left-2" src="/img/vip-bg.png" alt="">
                <div class="text-10 relative left-4 z-2 color-#ffffff">{{ 'VIP' + userStore.user.curVip }}
                </div>
              </div>
            </div>
            <div><span class="color-#677589 text-10">{{ t("home_page.login_gold") }} :</span><span
                class="color-#172029 font-bold"> 9988999.99</span></div>
          </div>
        </div>
        <!-- 侧边菜单栏 -->
        <div class="flex  justify-between mt-10 ">
          <!-- 左侧菜单 -->
          <div>
            <div class="menu w-85 h-50  flex flex-col items-center justify-center   mb-3 cursor-pointer"
              :class="{ 'active-menu-item': active === index }" v-for="(item, index) in menuList" :key="index"
              @click="getGame(item, index)">
              <img v-show="active === index" :src="item.url" alt="" class="w-20">
              <img v-show="active != index" :src="item.urls" alt="" class="w-20">
              <span class="text-12">{{ t(item.title) }}</span>
            </div>
          </div>
          <!-- 右侧内容 -->
          <div class="right-cont w-100%  pl-5 overflow-y-scroll" ref="rightContRef" @touchstart="onTouchStart"
            @touchend="onTouchEnd">
            <van-grid :column-num="columnNum" :border="false" :class="active == 0 || active == 1 ? 'two' : 'one'">
              <van-grid-item v-for="v in gameArr" :key="v.id" @click="goDetail(v)">
                <!-- 2图 -->
                <div v-if="columnNum === 2" class="relative">
                  <!-- 2图 -->
                  <img class="w-30 h-30 absolute left-0 top-0" :src="v.logo" />
                  <img class="w-126 h-90 rounded-t-10" :src="v.img" />
                  <div class="w- full px-7 flex justify-between items-center bg-#ffffff rounded-b-10">
                    <div class=" text-12 py-3 my-5 mx-0 overflow-hidden whitespace-nowrap text-ellipsis">{{
                      v.name }}
                    </div>
                    <van-icon size="18" @click.stop="v.like = !v.like" :name="v.like ? 'like' : 'like-o'"
                      :color="v.like ? 'red' : '#cccccc'" />
                  </div>
                </div>
                <!-- 1图 -->
                <div v-else class="relative">
                  <div
                    class="right-item w-full h-105 relative flex items-center justify-between rounded-10 border-1 border-#ffffff "
                    :class="whatType(v.type, v.like)">
                    <div class="w-[100%] h-125 py-16 px-15 relative flex justify-between items-start flex-col">

                      <div class="flex items-center ">
                        <div class="rate-text font-bold text-10 color-#181b2d pt-2"> {{
                          t('home_page.rightCont.infinite')
                        }},{{
                            t('home_page.rightCont.high') }}</div>
                        <i class="rate-text font-bold text-20 color-#1691e8 mt-2 ml-5">1.9%</i>
                      </div>
                      <div class="pl-4 flex items-center">
                        <img src="/img/view.png" alt="" class="w-14 h-12 mr-5">
                        <span class="text-12 text-[var(--c-text)]">1234212</span>
                      </div>
                    </div>
                  </div>
                  <!-- <div class="maintence w-full absolute  font-bold text-center" v-if="v.like">
                    <div class="">{{ t('home_page.rightCont.maintenance') }}</div>
                    <div>12月11日 16:32~17:00</div>
                  </div> -->
                </div>
              </van-grid-item>
            </van-grid>
          </div>
        </div>
      </van-sticky>
    </div>
    <van-popup v-model:show="show" position="bottom">
      <div class="p-20">
        <div v-for="v in langArr" :key="v.value" class="flex items-center justify-between h-60" @click="changeLang(v)">
          <div class="flex items-center ">
            <div class="w-39 h-39 bg-#ebf5ff rounded-full flex justify-center items-center"> <img :src="v.url" alt=""
                class="w-24"></div>
            <div>{{ v.name }}</div>
          </div>
          <div>
            <img v-if="v.value == curLangObj.value && v.checked" src="/img/select_lang.png" alt="" class="w-12">
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style lang="css" scoped>
@keyframes zoomShake {
  0% {
    transform: scale(1);
  }

  25% {
    transform: scale(1.15);
  }

  50% {
    transform: scale(0.95);
  }

  75% {
    transform: scale(1.05);
  }

  100% {
    transform: scale(1);
  }
}

.rate-text.animate {
  animation: zoomShake 0.6s linear;
}

.right-cont {
  height: 416px;
}

::v-deep .van-notice-bar__wrap {
  font-size: 14px;
}

.home-btn {
  background: url('/img/home_btn.png') no-repeat center center;
  background-size: 100% 100%;
  color: #6d788e;
  text-align: center;
  padding: 6px 0px;
  font-weight: bold;
  font-size: 14px;
}

.maintence {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.menu {
  /* background: url('~/assets/images/un-menu-bg.png') no-repeat; */
  background: url('/img/un-menu-bg.png') no-repeat center center;
  background-size: 100% 100%;
  color: var(--c-text);
  font-size: 12px;

  /* box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); */
}

.rebate {
  /* background: url('/img/rebate-bg.png') no-repeat center center; */
  width: 172px;
  background-size: cover;
  height: 18px;
}

.high {
  display: inline-block;
  padding: 1px 0 1px 5px;
  background: #ffffff;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}

.inifite {
  /* padding: 0 15px 0 5px; */
  width: 60%;
  padding: 0 25px 0 18px;
  font-size: 12px;
  background: url('/img/rebate2-bg.png') no-repeat center center;
  background-size: 100% 100%;
  border-bottom-right-radius: 17px;
  border-top-right-radius: 17px;
}

.right-item-luva {
  background: url('/img/LUVA_bg.png') no-repeat center center;
  background-size: 100% 100%;
  border-color: 1px solid #e0eef6;
  width: 260px;
}

.right-item-jl {
  background: url('/img/JL_bg.png') no-repeat center center;
  background-size: 100% 100%;
  border-color: 1px solid #e0eef6;
  width: 260px;
}

.right-item-pp {
  background: url('/img/PP_bg.png') no-repeat center center;
  background-size: 100% 100%;
  border-color: 1px solid #e0eef6;
  width: 260px;
}

.right-item-pg {
  background: url('/img/PG_bg.png') no-repeat center center;
  background-size: 100% 100%;
  border-color: 1px solid #e0eef6;
  width: 260px;
}

/* ::v-deep  .van-grid-item__content {
  padding: 0 !important;
  background: transparent;
  border-radius: 5px;
  margin-bottom: 10px;
} */
::v-deep .two .van-grid-item__content {
  padding: 0 !important;
  background: transparent;
  border-radius: 5px;
  margin-bottom: 10px;
}

::v-deep .two .van-grid-item:nth-child(odd) .van-grid-item__content {
  margin-right: 4px;
}

::v-deep .one .van-grid-item__content {
  padding: 0 !important;
  background: transparent;
  border-radius: 5px;
  margin-bottom: 5px;
}

::v-deep .login .van-button--small {
  color: var(--c-text);
  font-size: 12px;
  font-stretch: normal;
}

::v-deep .van-popup--bottom {
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}

.van-notice-bar {
  background: transparent;
  padding: 10px 0;
}

.active-menu-item {
  background: url('/img/menu-bg.png') no-repeat center center;
  /* border-color: var(--c-primary); */
  background-size: 100% 100%;
  font-weight: bold;
  color: #ffffff;
  /* box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); */
}

.rate {
  border-bottom: 1px solid gray;
  border-right: 1px solid gray;
}

.text-stroke {
  font-weight: bold;
  /* 描边宽度和颜色 */
  -webkit-text-stroke: 1px #2aa1ec;
  /* 文字填充色 */
  color: rgb(255, 255, 255);
}
</style>